package com.feinno.module.security.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.feinno.framework.common.dao.support.PageInfo;
import com.feinno.framework.common.exception.BusinessException;
import com.feinno.framework.common.service.EntityServiceImpl;
import com.feinno.framework.utils.Dates;
import com.feinno.module.security.dao.MenuDao;
import com.feinno.module.security.domain.Menu;
import com.feinno.module.security.service.MenuService;
import com.google.common.collect.Maps;

@Service("menuService")
public class MenuServiceImpl extends EntityServiceImpl<Menu, MenuDao> implements
		MenuService {

	@Override
	public List<Object> queryAuthorisedMenus(Long userId) {
		return getEntityDao().queryAuthorisedMenus(userId);
	}

	@Override
	public void moveUp(Long id) {
		try {
			Menu menu = get(id);
			Date current = menu.getOrderTime();
			Menu perv = null;
			
			long count = getEntityDao().getCountByGtOrderTime(current);
			if(count > 0){
				PageInfo<Menu> pageInfo = new PageInfo<Menu>(1,(int)count);
				Map<String,Boolean> sortMap = Maps.newLinkedHashMap();
				sortMap.put("showState", true);
				sortMap.put("orderTime", false);
				Map<String,Object> searchMap = Maps.newHashMap();
				searchMap.put("GT_orderTime", Dates.format(current, Dates.CHINESE_DATETIME_FORMAT_LINE));
				pageInfo = getEntityDao().query(pageInfo, searchMap, sortMap);
				if(pageInfo.getPageResults() != null && pageInfo.getPageResults().size() > 0){
					perv = pageInfo.getPageResults().get(0);
				}
			}

			if(perv != null){
				menu.setOrderTime(perv.getOrderTime());
				perv.setOrderTime(current);
				save(perv);
			}else{
				menu.setOrderTime(new Date());
			}
			save(menu);
		} catch (Exception e) {
			throw new BusinessException("菜单上移失败", e);
		}
		
	}

	@Override
	public void moveTop(Long id) {
		try {
			Menu menu = get(id);
			menu.setOrderTime(new Date());
			save(menu);
		} catch (Exception e) {
			throw new BusinessException("菜单置顶失败", e);
		}
	}

}
